package com.ugoodtech.mdcc.web.controller;

import com.ugoodtech.mdcc.core.LogConstants;
import com.ugoodtech.mdcc.core.domain.Department;
import com.ugoodtech.mdcc.core.domain.Role;
import com.ugoodtech.mdcc.core.domain.User;
import com.ugoodtech.mdcc.core.domain.UserProfile;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.utils.BaseUtil;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import com.ugoodtech.mdcc.web.dto.UserProfileResponse;
import com.ugoodtech.mdcc.web.service.UserProfileService;
import com.ugoodtech.mdcc.web.service.UserService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;


/**
 * Copyright © 2013 All Rights Reserved, Ugood Technology, Inc.
 */
@Api(description = "管理人员接口")
@RestController
@RequestMapping("/systemUser")
public class SystemUserController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(SystemUserController.class);
    @Autowired
    UserRepository systemUserRepository;
    @Autowired
    UserService systemUserService;

    @Autowired
    FeedbackRepository feedbackRepository;

    @Autowired
    UserProfileService userProfileService;

    @Autowired
    UserProfileRepository userProfileRepository;

    @Autowired
    DepartmentRepository departmentRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RoleRepository roleRepository;

//    @RequestMapping(value = "/getUsers", method = RequestMethod.GET)
//    public JsonResponse getUsers(
//            @RequestParam(value = "searchParam") String searchParam, Pageable pageable) throws Exception {
//        isUserLogin();
//        Page<User> systemUsers = systemUserService.queryUser(searchParam, Constants.ROLE_ADMIN, pageable);
//        return JsonResponse.successResponseWithPageData(systemUsers);
//    }

    @ApiOperation("管理员列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "data", response = User.class)
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = false, paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getAllDepartment(@ApiParam("类型") @RequestParam(value = "userType", required = false) String userType,
                                         @ApiParam("员工编号") @RequestParam(value = "code", required = false) String code,
                                         @ApiParam("姓名") @RequestParam(value = "name", required = false) String name,
                                         @ApiParam("手机号码") @RequestParam(value = "telephone", required = false) String telephone,
                                         @ApiParam("关联部门") @RequestParam(value = "departmentIds", required = false) Long[] departmentIds,
                                         Pageable pageable) {
        isUserLogin();
        Page<UserProfile> userProfile = userProfileService.queryAadminSystemUser(userType, code, name, telephone, departmentIds, pageable);
        return JsonResponse.successResponseWithPageData(BaseUtil.getDtoPage(userProfile, pageable, UserProfileResponse.class));
    }


    @ApiOperation("添加管理人员")
    @RequestMapping(value = "/systemUser", method = RequestMethod.POST)
    public JsonResponse addSystemUser(
            @ApiParam(value = "员工编号", required = true) @RequestParam(required = false) String code,
            @ApiParam(value = "姓名", required = false) @RequestParam(required = false) String name,
            @ApiParam(value = "手机号码", required = false) @RequestParam(required = false) String telephone,
            @ApiParam(value = "关联部门", required = true) @RequestParam(required = false) Long departmentId,
            @ApiParam(value = "角色id", required = true) @RequestParam(required = false) Long roleId
    ) throws Exception {
        isUserLogin();

        JsonResponse jsonResponse= userProfileService.createSystemUser(code, name, telephone, departmentId, roleId);
       if(jsonResponse.isSuccess()){
           userLogService.addUserLog(this.getCurrentUser(),null,
                   LogConstants.operate_type_add,
                   LogConstants.business_type_people,null,null);
       }
       return jsonResponse;
    }


    @ApiOperation("编辑管理人员")
    @RequestMapping(value = "/editSystemUser", method = RequestMethod.POST)
    public JsonResponse editSystemUser(
            @ApiParam(value = "员工id", required = true) @RequestParam(required = true) Long userId,
            @ApiParam(value = "员工编号", required = true) @RequestParam(required = false) String code,
            @ApiParam(value = "姓名", required = false) @RequestParam(required = false) String name,
            @ApiParam(value = "手机号码", required = false) @RequestParam(required = false) String telephone,
            @ApiParam(value = "关联部门", required = true) @RequestParam(required = false) Long departmentId,
            @ApiParam(value = "角色id", required = true) @RequestParam(required = false) Long roleId) {
        isUserLogin();
        UserProfile userCode = userProfileRepository.findBySerialNumber(code);
        if (userCode != null && !userCode.getId().equals(userId)) {
            return JsonResponse.errorResponseWithError("抱歉", "此编号已经存在，请重新输入");
        }
        userCode = userProfileRepository.findByTelephone(telephone);
        if (userCode != null && !userCode.getId().equals(userId)) {
            return JsonResponse.errorResponseWithError("抱歉", "此手机号码已经存在，请重新输入");
        }

        Role role = roleRepository.findOne(roleId);
        Department department = departmentRepository.findOne(departmentId);
        UserProfile userProfile = userProfileRepository.findOne(userId);
        User user = userProfile.getUser();
        user.setUsername(telephone);
        systemUserRepository.save(user);
        userProfile.setSerialNumber(code);
        userProfile.setRealName(name);
        userProfile.setNickname(name);
        userProfile.setTelephone(telephone);
        userProfile.setDepartment(department);
        userProfileRepository.save(userProfile);
        userLogService.addUserLog(this.getCurrentUser(),null,
                LogConstants.operate_type_edit,
                LogConstants.business_type_people,null,null);
        return JsonResponse.successResponse();
    }


//    @ApiOperation("修改用户")
//    @RequestMapping(value = "/editUser", method = RequestMethod.POST)
//    public JsonResponse editUser(@ApiParam(value = "用户数据库id", required = true) @RequestParam Long systemUserId,
//                                       @ApiParam(value = "姓名", required = false) @RequestParam(required = false) String realName,
//                                       @ApiParam(value = "手机号码", required = false) @RequestParam(required = false) String telephone,
//                                       @ApiParam(value = "角色id", required = true) @RequestParam(required = true) Long systemUserRoleId) throws Exception {
//        isUserLogin();
//        User systemUser = systemUserRepository.findOne(systemUserId);
////        systemUser.setRealName(realName);
//        systemUser.setUsername(realName);
////        systemUser.setTelephone(telephone);
////        Set<UserRole> roles=systemUser.getRoles();
////        if(null==roles||roles.size()==0){
////            roles=new HashSet<>();
////        }
////        roles.add(systemUserRoleRepository.findOne(systemUserRoleId));
////        systemUser.setRoles(roles);
//
////        systemUser.setPassword(null);
//        systemUserRepository.save(systemUser);
//        return JsonResponse.successResponse();
//    }

//    @ApiOperation("删除单条用户")
//    @RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
//    public JsonResponse deleteUsers(
//            @ApiParam(value = "用户数据库id", required = true) @RequestParam Long systemUserId) throws Exception {
//        isUserLogin();
//
//        User systemUser = systemUserRepository.findOne(systemUserId);
//        systemUserService.delete(systemUserId);
//        systemUser.setUsername(systemUser.getUsername() + "_" + System.currentTimeMillis());
//        systemUser.setDeleted(true);
//        systemUser.setEnabled(false);
//        systemUserRepository.save(systemUser);
//        return JsonResponse.successResponse();
//    }
//
//    @ApiOperation("删除多条用户")
//    @RequestMapping(value = "/deleteUsers", method = RequestMethod.POST)
//    public JsonResponse deleteUsers(
//            @ApiParam(value = "用户数据库id组成的数组", required = true) @RequestParam Long[] systemUserIds) throws Exception {
//        isUserLogin();
//        if (null != systemUserIds && systemUserIds.length > 0) {
//            systemUserService.delete(Arrays.asList(systemUserIds));
//            for (Long id : systemUserIds) {
//                User systemUser = systemUserRepository.findOne(id);
//                systemUser.setUsername(systemUser.getUsername() + "_" + System.currentTimeMillis());
//                systemUser.setDeleted(true);
//                systemUser.setEnabled(false);
//                systemUserRepository.save(systemUser);
//            }
//            return JsonResponse.successResponse();
//        } else {
//            return JsonResponse.errorResponseWithError("fail", "error systemUser id");
//        }
//
//    }

//    @ApiOperation("修改用户密码")
//    @RequestMapping(value = "/changeUserPwd", method = RequestMethod.POST)
//    public JsonResponse changeUserPwd(
//            @ApiParam(value = "旧密码", required = true) @RequestParam(value = "oldPwd") String oldPwd,
//            @ApiParam(value = "新密码", required = true) @RequestParam(value = "newPwd") String newPwd) throws Exception {
//
//        User currentUser = this.getCurrentUser();
//        if (null == currentUser) {
//            return JsonResponse.errorResponseWithError("", "please login again");
//        } else {
//            logger.debug("当前登录用户id:" + currentUser.getId());
//        }
//        if (oldPwd.equals(newPwd)) {
//            return JsonResponse.errorResponseWithError("", "new password can not be the same as the original password ");
//        }
//        try {
//            boolean result = systemUserService.changePassword(currentUser, newPwd, oldPwd);
//            if (result) {
//                return JsonResponse.successResponseWithData("success");
//            } else {
//                return JsonResponse.errorResponseWithError("", "failed,Original password error");
//            }
//
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            logger.debug("failed,Original password error");
//            return JsonResponse.errorResponseWithError("", "failed,Original password error");
//
//        }
//    }

//    @RequestMapping(value = "/getFeedbacks", method = RequestMethod.GET)
//    public JsonResponse getFeedbacks(
//            Pageable pageable) throws Exception {
//        Pageable pageable1 = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), new Sort(Sort.Direction.DESC, "creationTime"));
//        Page<Feedback> feedbacks = feedbackRepository.findAll(pageable1);
//        return JsonResponse.successResponseWithPageData(feedbacks);
//    }

//    @ApiOperation("重置用户密码")
//    @RequestMapping(value = "/restPassword", method = RequestMethod.POST)
//    public JsonResponse restPassword(@ApiParam(value = "用户数据库id", required = true) @RequestParam(value = "systemUserId") Long systemUserId) {
//        isUserLogin();
//        User systemUser = systemUserRepository.findOne(systemUserId);
//        if (systemUser == null) {
//            return JsonResponse.errorResponseWithError("500", "未找到此系统用户");
//        }
//        systemUser.setPassword(passwordEncoder.encode(Constants.INIT_PASSWORD));
//        systemUserRepository.save(systemUser);
//        return JsonResponse.successResponse();
//    }

    @ApiOperation("激活/禁用系统用户")
    @RequestMapping(value = "/enableUser", method = RequestMethod.POST)
    public JsonResponse enableUser(@ApiParam(value = "用户数据库id", required = true) @RequestParam(value = "systemUserId") Long systemUserId,
                                   @ApiParam(value = "激活/禁用", required = true) @RequestParam(value = "enabled") boolean enabled) {
        isUserLogin();
        UserProfile systemUser = userProfileRepository.findOne(systemUserId);
        if (systemUser == null) {
            return JsonResponse.errorResponseWithError("500", "未找到此系统用户");
        }
        if (systemUser.isEnabled() == false && enabled == false) {
            return JsonResponse.errorResponseWithError("500", "该用户已被禁用");
        }
        if (systemUser.isEnabled() == true && enabled == true) {
            return JsonResponse.errorResponseWithError("500", "该用户已被激活");
        }
        systemUser.setEnabled(enabled);
        User user = systemUser.getUser();
        user.setEnabled(enabled);
        userProfileRepository.save(systemUser);
        systemUserRepository.save(user);
        return JsonResponse.successResponse();
    }


}
